import { openHandler, sendHandler, setProps, setRequestHeader } from '../xhr/proxy'
import { MSG_TYPES } from '../utils/MESSAGE_TYPES'
let incrementId = 0;
(function () {
  const O_XHR = XMLHttpRequest

  const REQUEST_MAP = {}
  let PROXY_ROUTES = []

  // 发送同步请求
  window.postMessage({ event: MSG_TYPES.matchingReq })
  console.log('inject matchingReq')

  window.addEventListener('message', function (msg) {
    const { data, headers } = msg
    if (data.event === MSG_TYPES.response) {
      const synchro = REQUEST_MAP[data.id]
      Object.entries(data.data).forEach(([key, value]) => {
        synchro[key] = value
      })
      synchro.getAllResponseHeaders = function () {
        return headers
      }
      synchro.origin.onreadystatechange()
    } else if (data.event === MSG_TYPES.matchingUpdate) {
      PROXY_ROUTES = data.data || []
    }
  })
  function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  }

  function ProxyXHR() {
    const xhr = new O_XHR()
    xhr.bgReqId = incrementId++
    REQUEST_MAP[xhr.bgReqId] = {
      origin: xhr
    }
    return new Proxy(xhr, {
      set(target, prop, value, receiver) {
        switch (prop) {
          case 'responseType':
            setProps(xhr, prop, value); break;
        }
        target[prop] = value;
        return true;
      },
      get(target, property, receiver) {
        console.log('get', property, target[property])
        // REQUEST_MAP 中的 属性是background 响应response写入的
        if (property in REQUEST_MAP[xhr.bgReqId]) {
          if (property === 'response' && target.responseType === 'blob') {
            return dataURLtoBlob(REQUEST_MAP[xhr.bgReqId][property])
          }
          return REQUEST_MAP[xhr.bgReqId][property]
        }
        switch (property) {
          case 'open':
            return openHandler(xhr, PROXY_ROUTES)
          case 'send':
            return sendHandler(xhr, PROXY_ROUTES)
          case 'setRequestHeader':
            return setRequestHeader(xhr, PROXY_ROUTES)
          case 'getAllResponseHeaders':
            return function () {
              return xhr.getAllResponseHeaders()
            }
          default:
            return target[property]
        }
      }
    })
  }
  window.XMLHttpRequest_ORIGIN = O_XHR
  window.XMLHttpRequest = ProxyXHR
})()